﻿#region Copyright ©2008-2009, Technische Universitaet Muenchen
// ====================================================================================================
//
// Last Changed by       $Author: then $
// Last Changed Date     $LastChangedDate: 2009-06-16 17:17:03 +0200 (Tue, 16 Jun 2009) $
// Last Changed Revision $Rev: 209 $
//
// ====================================================================================================
#endregion

using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Tum.CollabXT.VModellXT
{
    public static class Helper
    {
        /// <summary>
        /// Tests whether an object is null.
        /// If so an exception is thrown, else the object is returned.
        /// </summary>
        /// <typeparam name="T">Type of the object to be null-checked.</typeparam>
        /// <param name="val">The object to be null-checked.</param>
        /// <param name="exceptionText">Text of the exception to be thrown on null.</param>
        /// <returns>The parameter passed to val.</returns>
        public static T ThrowExceptionWhenNull<T>(T val, string exceptionText)
        {
            // GKa: val.Equals geht schon schief, wenn val null ist.
            // Das fuehrt zwar auch zu einer NullReferenceException
            // aber uns entgeht die schoene Fehlermeldung in exceptionText
            //if (val.Equals(default(T)))
            if (val == null)
                throw new NullReferenceException(exceptionText);
            else
                return val;
        }

        /// <summary>
        /// Strips a string of html tags.
        /// </summary>
        /// <param name="str">String to be stripped</param>
        /// <returns>Stripped string</returns>
        public static string StripHtmlString(string str)
        {
            string decodedStr = HttpUtility.HtmlDecode(str);
            try
            {
                //Replace paragraph ends with linebreaks
                decodedStr = decodedStr.Replace("</p>", Environment.NewLine);

                decodedStr = RemoveHtmlTagsRegEx.Replace(decodedStr, "");
                return decodedStr;
            }
            catch
            {
                return decodedStr;
            }
        }
        private static Regex RemoveHtmlTagsRegEx = new Regex(@"<[^>]*>|\]\]>", RegexOptions.Compiled);
    }
}
